package cn.t.modules.scheduler.core.schedule.task;

import cn.t.modules.scheduler.common.enums.ScheduleStatus;
import cn.t.modules.scheduler.common.enums.ScheduleType;
import cn.t.modules.scheduler.core.SpringBeanContext;
import cn.t.modules.scheduler.core.ScheduleMailSender;
import cn.t.modules.scheduler.core.SqlProcessor;
import cn.t.modules.scheduler.core.schedule.repository.po.SchedulePo;
import com.alibaba.fastjson2.JSON;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Set;

/**
 * 通知任务
 * @author 陶敏麒
 * @date 2024/3/5 15:09
 */
@Setter
@Slf4j
public class DelayMailTask extends BaseTask {

    private static final DateTimeFormatter TASK_ID_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
    public DelayMailTask(MailContent content, String taskName, long execTs) {
        super("MT-" + TASK_ID_FORMATTER.format(LocalDateTime.now()), taskName, JSON.toJSONString(content), 0, execTs);
    }

    public DelayMailTask(SchedulePo schedulePo) {
        super(schedulePo.getScheduleId(), schedulePo.getScheduleName(), schedulePo.getContent(), schedulePo.getVersion(), schedulePo.getExecTimeTs());
        super.taskId = schedulePo.getId();
    }


    /**
     * 执行提醒
     */
    @Override
    protected void execute() {
        log.info("[延时邮件任务][{}]开始执行,当前任务计划id[{}]", super.scheduleName, super.scheduleId);
        var sqlProcessor = SpringBeanContext.getBean(SqlProcessor.class);
        try {
            var property = JSON.parseObject(super.getContent(), MailContent.class);
            // 判断版本号

            var mailSender = SpringBeanContext.getBean(ScheduleMailSender.class);
            mailSender.sendMail(property.to, null, this.scheduleName, property.content);
            // 执行成功则更新数据
            sqlProcessor.updateStatus(super.taskId, ScheduleStatus.COMPLETED, "执行完成", super.version);
        } catch (Exception e) {
            log.error("[延时邮件任务]执行失败, 当前任务计划id[{}], 错误消息:{}", super.scheduleId, e.getMessage());
            sqlProcessor.updateStatus(super.taskId, ScheduleStatus.FAILURE, e.getMessage(), super.version);
        }
    }

    @Override
    public String type() {
        return ScheduleType.MAIL.name();
    }

    @Setter
    @Getter
    public static class MailContent {
        public MailContent(String content, Set<String> to) {
            this.content = content;
            this.to = to;
        }

        private String content;
        private Set<String> to;
    }
}
